package com.xzz.tree;

import java.util.*;

/**
 * @author: hhz
 * @create: 2022-01-20 15:17
 * 103. 二叉树的锯齿形层序遍历
 **/
public class ZigzagLevelOrder {
    public static void main(String[] args) {
        TreeNode node1 = new TreeNode(1);
        TreeNode node2 = new TreeNode(2);
        TreeNode node3 = new TreeNode(3);
        TreeNode node4 = new TreeNode(4);
        TreeNode node5 = new TreeNode(5);
        node1.left = node2;
        node1.right = node3;
        node3.left = node4;
        node3.right = node5;
        System.out.println(zigzagLevelOrder(node1));
    }
    public static List<List<Integer>> zigzagLevelOrder(TreeNode root) {

        List<List<Integer>> res = new ArrayList<>();
        if(root==null){
            return res;
        }
        Queue<TreeNode> queue = new LinkedList<>();
        queue.offer(root);
        boolean flag = true;
        while (!queue.isEmpty()){

            int size = queue.size();
            LinkedList<Integer> list = new LinkedList<>();
            for (int i = 0; i < size; i++) {
                TreeNode treeNode = queue.poll();
                if(flag){
                    list.addLast(treeNode.val);
                }else {
                    list.addFirst(treeNode.val);
                }
                if(treeNode.left!=null){
                   queue.offer(treeNode.left);
                }
                if(treeNode.right!=null){
                    queue.offer(treeNode.right);
                }
            }
            flag = !flag;
            res.add(list);
        }
        return res;
    }


}
